import { getUserProfileAPI, loginAPI } from '@/api/user'
import router from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    profile: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    delToken(state) {
      state.token = null
      removeToken()
    },
    setProfile(state, profile) {
      state.profile = profile
    }
  },
  actions: {
    // 登录
    async login(context, data) {
      // 1. 发送请求
      // 2. 获取toke
      const { data: { token }} = await loginAPI(data)
      // 3. 提交给mutation
      context.commit('setToken', token)
    },
    // 退出登录
    logout(context) {
      context.commit('delToken')
      context.commit('setProfile', {})
      router.commit('menu/resetMenuList')
    },
    async getUserProfile(context) {
      const res = await getUserProfileAPI()
      console.log('用户权限信息', res)
      context.commit('setProfile', res.data)
      return res.data.permissions
    }
  }
}
